/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zh.rxharmony.schedulers;

import com.zh.rxharmony.plugins.RxHarmonyPlugins;
import io.reactivex.Scheduler;
import ohos.eventhandler.EventRunner;

/**
 * HarmonyOS，线程调度器工厂
 */
public final class HarmonySchedulers {
    /**
     * 主线程调度器
     */
    private static final Scheduler MAIN_THREAD =
            RxHarmonyPlugins.initMainThreadScheduler(() -> MainHolder.DEFAULT);

    /**
     * 单例，保存主线程调度器
     */
    private static final class MainHolder {
        static final Scheduler DEFAULT = new EventHandlerScheduler(new EventHandlerScheduler.WithIdEventHandler(EventRunner.current()));
    }

    /**
     * 工具类，隐藏构造方法，如果被反射，抛出异常
     */
    private HarmonySchedulers() {
        throw new AssertionError("No instances.");
    }

    /**
     * 获取主线程调度器
     */
    public static Scheduler mainThread() {
        return RxHarmonyPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    /**
     * 可以指定EventRunner，类似Android中的Looper轮训器，所以调度器可以绑定在非主线程中
     */
    public static Scheduler from(EventRunner eventRunner) {
        //判空
        if (eventRunner == null) throw new NullPointerException("looper == null");
        //根据配置，创建对应的主线程调度器
        return new EventHandlerScheduler(new EventHandlerScheduler.WithIdEventHandler(eventRunner));
    }
}
